#ifndef __NCE_BUFFER_H__
#define __NCE_BUFFER_H__

#include <iostream>
#include <vector>

using namespace std;

namespace nce
{

class InputBuffer
{
public:
    InputBuffer() : _buf(NULL), _len(0), _cur(0) {}
	
	~InputBuffer() { reset(); }
	
    void setBuf(const char *buf, size_t len)
    {
        reset();
		
		_buf = buf;
        _len = len;
        _cur = 0;
    }

	void read(int &i)
	{
        cout << "before read int" << endl;
		const char *p = _buf+_cur;
		_cur += sizeof(int);
		i = *(int *)p;
        cout << "after read int " << i << endl;
	}
	
	// read string from the buffer
	// the first char of the string equals s.size()+1.
    void read(string &s)
    {
        cout << "before read string" << endl;
        const char *p = _buf+_cur;
        char len = *p;
        _cur += len;
        s.assign(p+1, _buf+_cur);
        cout << "after read string " << s << endl;
    }
	
	void reset()
	{
		if (_buf != NULL) 
		{
			delete [] _buf;
			_buf = NULL;	
		}
		
		_len = 0;
		_cur = 0;
	}
	
//private:
    const char 	*_buf;
    size_t      _len;
    size_t      _cur;
};

class OutputBuffer
{
public:
	const char *getBuf() const
    {
        return &_buf[0];
    }

    size_t getLen() const
    {
        return _buf.size();
    }

	void write(int i)
	{
        char *pc = (char *)&i;
        cout << "before write int " << i << endl;
        _buf.insert(_buf.end(), pc, pc+sizeof(int));
        cout << "after write int " << i << endl;
	}
	
    void write(const string &s)
    {
        cout << "before write string " << s << endl;
        _buf.push_back(s.size()+1);
        _buf.insert(_buf.end(), s.c_str(), s.c_str()+s.size());
        cout << "after write string " << s << endl;
    }
	
	void reset()
	{
		_buf.clear();
	}

private:
    vector<char> _buf;
};
    
}

#endif
